import { HttpService, Inject, Injectable } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { WeChatMiniProgramsConfig } from 'src/config/we-chat-mini-program.config';
import { Code2Session } from './code2session.interface';

@Injectable()
export class TokenService {
  constructor(
    @Inject(WeChatMiniProgramsConfig.KEY)
    private weChatMiniProgramsConfig: ConfigType<
      typeof WeChatMiniProgramsConfig
    >,
    private jwtService: JwtService,
    private readonly httpService: HttpService,
  ) {}

  /**
   * 登录
   * @param openid 用户唯一标识
   * @returns 签发的令牌
   */
  async login(userId: string) {
    const payload = { userId };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  /**
   * code to session
   * @param js_code 微信小程序登录时获取的 code
   */
  code2Session(js_code: string) {
    const { url, ...params } = this.weChatMiniProgramsConfig;

    return this.httpService
      .get<Code2Session>(url, {
        params: {
          js_code,
          ...params,
        },
      })
      .toPromise();
  }
}
